package com.ang.juc.n6;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@Slf4j
public class Test1 {

    public static void main(String[] args) throws InterruptedException {
        /**
         * TicketWendow会出现售票+余票>3000，出现超卖
         */

        //共享变量
//        TicketWendow ticketWendow = new TicketWendow(3000);
        TicketWendow2 ticketWendow = new TicketWendow2(3000);

        List<Integer> list = new Vector<>();
        List<Thread> threadList = new ArrayList<>();
        IntStream.range(0,2000).forEach(i->{
            Thread t = new Thread(() -> {
                int sell = ticketWendow.sell();
                list.add(sell);
            });
            t.start();
            threadList.add(t);
        });

        //所有线程终止后
        for (Thread thread : threadList) {
            thread.join();
        }

        System.out.println("售票："+list.stream().mapToInt(Integer::intValue).sum());
        System.out.println("余票："+ticketWendow.getCount());
    }

    /**
     * 账户操作类
     * 不安全
     */
    @Data
    static class TicketWendow{
        private Integer count;

        public TicketWendow(Integer count){
            this.count = count;
        }

        public int sell(){
            if(count > 0){
                count = count -1;
                return 1;
            }
            return 0;
        }
    }

    /**
     * 安全
     */
    @Data
    static class TicketWendow2{
        private Integer count;

        public TicketWendow2(Integer count){
            this.count = count;
        }

        public synchronized int sell(){
            if(count > 0){
                count = count -1;
                return 1;
            }
            return 0;
        }
    }
}
